package com.yanqu.road.server.manager.chefduel;

import com.google.protobuf.AbstractMessage;
import com.yanqu.road.dao.impl.cross.chefduel.CrossChefDuelDaoImpl;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.chefduel.CrossChefDuel2Rank;
import com.yanqu.road.entity.activity.chefduel.CrossChefDuel2RankListModel;
import com.yanqu.road.entity.activity.chefduel.process2.ChefDuelUpUser;
import com.yanqu.road.entity.activity.chefduel.process3.ChefDuel3BanquetReward;
import com.yanqu.road.entity.activity.chefduel.process3.ChefDuel3EndBanquet;
import com.yanqu.road.entity.activity.chefduel.process3.ChefDuel3OpenItem;
import com.yanqu.road.entity.activity.chefduel.process3.ChefDuel3Table;
import com.yanqu.road.entity.activity.chefduel.rank.CampRank;
import com.yanqu.road.entity.activity.chefduel.rank.CampRankListModel;
import com.yanqu.road.entity.log.chefduel.LogChefDuel3End;
import com.yanqu.road.entity.log.chefduel.LogChefDuel3Open;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.chefduel.ChefDuelProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.log.CrossAutoLogMgr;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.pb.chefduel.CrossChefDuelPb;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CrossChefDuel3 {

    private Logger logger = LogManager.getLogger(CrossChefDuel3.class.getName());

    private Map<Integer,Object> lockMap = new ConcurrentHashMap<>();

    private ActivityInfo activityInfo;

    private Map<Long, ChefDuelUpUser> chefDuelMap = new ConcurrentHashMap<>();
    private List<ChefDuelUpUser> needInsertUserList = new ArrayList<>();
    private List<ChefDuelUpUser> needUpdateUserList = new ArrayList<>();

    //阵营竞猜人气
    Map<Integer, Integer> campCountMap = new HashMap<>();
    //阵营积分
    CampRankListModel campRankListModel = new CampRankListModel();
    //阵营玩家榜单
    Map<Integer, CrossChefDuel2RankListModel> campUserRankMap = new ConcurrentHashMap<>();

    //用户id场次no
    private Map<Long,Map<Integer, ChefDuel3Table>> cookBoyTableMap = new ConcurrentHashMap<>();

    private List<ChefDuelUpUser> needSyncCookerList = new ArrayList<>();

    private List<ChefDuel3Table> syncTableList = new ArrayList<>();

    private List<ChefDuel3Table> syncOpenList = new ArrayList<>();

    private List<ChefDuel3Table> needInsertTableList = new ArrayList<>();
    private List<ChefDuel3Table> needUpdateTableList = new ArrayList<>();

    public int getActivityId(){
        return activityInfo.getActivityId();
    }

    public ActivityInfo getActivityInfo(){
        return activityInfo;
    }

    public String getChefDuel3BanquetTimes(String param){
        long homeUserId = Long.valueOf(param);
        if(cookBoyTableMap.containsKey(homeUserId)){
            return String.valueOf(cookBoyTableMap.get(homeUserId).size());
        }
        return "0";
    }

    public String getChefDuel3BanquetUserCount(String param){
        long homeUserId = Long.valueOf(param);
        if(cookBoyTableMap.containsKey(homeUserId)){
            int userCount = 0;
            for(ChefDuel3Table cookBoy3Table :new ArrayList<>( cookBoyTableMap.get(homeUserId).values())){
                userCount += cookBoy3Table.getChefDuel3JoinerMap().size();
            }
            return String.valueOf(userCount);
        }
        return "0";
    }

    private Map<Integer,Long> getPageJoinMap(Map<Integer,Long> joinerMap,int page,int num){
        Map<Integer,Long> resMap = new ConcurrentHashMap<>();
        int count = joinerMap.size();
        int index = (page - 1) * num;
        int resCount = 0;
        for(;index < count + num;index++){
            if(resCount++ == num){
                break;
            }
            if(joinerMap.size() > index){
                //joinerMap的key是位置，按照1开始
                Long userId = joinerMap.get(index + 1);
                resMap.put(index,userId);
            }else{
                break;
            }
        }
        return resMap;
    }

    public void getBanquetJoiner(long serverId,long userId,long homeUserId,int banquetId,int page,int num){
        if(page == 0){
            page = 1;
        }
        if(num == 0 || num > 100){
            num = 100;
        }
        ChefDuelProto.ChefDuel3BanquetJoinerRespMsg.Builder msg = ChefDuelProto.ChefDuel3BanquetJoinerRespMsg.newBuilder();
        msg.setRet(0);
        msg.setActivityId(getActivityId());
        msg.setHomeUserId(homeUserId);
        msg.setBanquetId(banquetId);
        if(cookBoyTableMap.containsKey(homeUserId) && cookBoyTableMap.get(homeUserId).containsKey(banquetId)){
            ChefDuel3Table cookBoy3Table = cookBoyTableMap.get(homeUserId).get(banquetId);
            Map<Integer,Long> joinerMap = cookBoy3Table.getChefDuel3JoinerMap();
            Map<Integer,Long> resMap = getPageJoinMap(joinerMap,page,num);
            for(Integer pos : resMap.keySet()){
                ChefDuelProto.ChefDuel3BanquetJoinerTempMsg.Builder tempMsg = ChefDuelProto.ChefDuel3BanquetJoinerTempMsg.newBuilder();
                tempMsg.setUserId(resMap.get(pos));
                tempMsg.setPos(pos);
                UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(resMap.get(pos));
                if(userBaseInfo == null){
                    continue;
                }
                tempMsg.setUserInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
                msg.addJoinerList(tempMsg);
            }
            msg.setUserCount(joinerMap.size());
        }
        YanQuMessage pbOpenerMsg = YanQuMessageUtils.buildMessage(Protocol.U_CHEF_DUEL3_GET_BANQUET_MEMBER, msg);
        MessageHelper.sendPacket(serverId, userId, pbOpenerMsg);
    }

    public void getUserBanquet(long serverId, long userId,long homeUserId){
            ChefDuelProto.ChefDuel3GetUserBanquetRespMsg.Builder msg = ChefDuelProto.ChefDuel3GetUserBanquetRespMsg.newBuilder();
            msg.setRet(0);
            if(cookBoyTableMap.containsKey(homeUserId)){
                ArrayList<ChefDuel3Table> cookBoy3Tables = new ArrayList<>(cookBoyTableMap.get(homeUserId).values());
                cookBoy3Tables.sort(Comparator.comparingLong(ChefDuel3Table::getOpenTime));
                Collections.reverse(cookBoy3Tables);
                int num = 0;
                for(ChefDuel3Table cookBoy3Table : cookBoy3Tables){
                    ChefDuelProto.ChefDuel3BanquetTempMsg.Builder tempMsg = ChefDuelProto.ChefDuel3BanquetTempMsg.newBuilder();
                    tempMsg.setBanquetId(cookBoy3Table.getNo());
                    tempMsg.setOpenItemId(cookBoy3Table.getOpenItemId());
                    tempMsg.setOpenTime((int)(cookBoy3Table.getOpenTime()/1000));
                    tempMsg.setUserCount(cookBoy3Table.getChefDuel3JoinerMap().size());
                    tempMsg.setIntegral(cookBoy3Table.getIntegral());
                    if (System.currentTimeMillis() - cookBoy3Table.getOpenTime() >= 3600*1000) {
                        tempMsg.setSelfJoin(false);
                    }else {
                        tempMsg.setSelfJoin(cookBoy3Table.getChefDuel3JoinerMap().containsValue(userId));
                    }
                    msg.addBanquetList(tempMsg);
                    num++;
                    if (num >= 50) {
                        break;
                    }
                }
            }
            YanQuMessage pbOpenerMsg = YanQuMessageUtils.buildMessage(Protocol.U_CHEF_DUEL3_GET_USER_BANQUET, msg);
            MessageHelper.sendPacket(serverId, userId, pbOpenerMsg);
    }

    public ChefDuel3BanquetReward getBanquetReward(long userId, int banquetId){
        ChefDuel3BanquetReward cookBoy3BanquetReward = new ChefDuel3BanquetReward();
        if(!cookBoyTableMap.containsKey(userId)){
            cookBoy3BanquetReward.setRet(GameErrorCode.E_CHEF_DUEL3_USER_NOT_MATCH);
            return cookBoy3BanquetReward;
        }
        ChefDuel3Table cookBoy3Table = cookBoyTableMap.get(userId).get(banquetId);
        if(null == cookBoy3Table){
            cookBoy3BanquetReward.setRet(GameErrorCode.E_CHEF_DUEL3_BANQUET_NOT_FOUND);
            return cookBoy3BanquetReward;
        }
        if(cookBoy3Table.getOverTime() == 0){
            cookBoy3BanquetReward.setRet(GameErrorCode.E_CHEF_DUEL3_BANQUET_NOT_OVER);
            return cookBoy3BanquetReward;
        }
        int integralId = CrossChefDuelActivityMgr.getChefDuel3IntegralItemId(activityInfo.getActivityId());
        cookBoy3BanquetReward.setReward(integralId + "=" + cookBoy3Table.getIntegral());
        cookBoy3BanquetReward.setIntegral(cookBoy3Table.getIntegral());
        cookBoy3BanquetReward.setUserCount(cookBoy3Table.getChefDuel3JoinerMap().size());
        cookBoy3BanquetReward.setOpenItemId(cookBoy3Table.getOpenItemId());
        return cookBoy3BanquetReward;
    }

    private ChefDuel3EndBanquet endTable(ChefDuel3Table cookBoy3Table){
        ChefDuel3EndBanquet cookBoy2EndBanquet = null;
        if(cookBoy3Table.getOverTime() == 0){
            ChefDuel3OpenItem cookBoy3OpenItem = CrossChefDuelActivityMgr.getChefDuel3OpenItem(getActivityId(),cookBoy3Table.getOpenItemId());
            int endType = 3;
            if(cookBoy3Table.getChefDuel3JoinerMap().size() >= cookBoy3OpenItem.getEatNum()){
                endType = 2;
            }
            cookBoy3Table.setOverTime(System.currentTimeMillis());
            cookBoy2EndBanquet = new ChefDuel3EndBanquet();

            //结束了加上没坐完的自动填充机器人那部分积分
            /*ChefDuel3OpenItem cookBoy3OpenItem = CrossChefDuelActivityMgr.getChefDuel3OpenItem(getActivityId(),cookBoy3Table.getOpenItemId());
            int needAddNum = cookBoy3OpenItem.getEatNum() - cookBoy3Table.getChefDuel3JoinerList().size();
            if(needAddNum > 0){
                long addIntegral = cookBoy3OpenItem.getIntegral() * needAddNum * CrossChefDuelActivityMgr.getChefDuel3RobotAdd(getActivityId()) / 1000;
                ChefDuelProto.CrossChefDuel3RobotJoinBanquetMsg.Builder msg = ChefDuelProto.CrossChefDuel3RobotJoinBanquetMsg.newBuilder();
                msg.setRet(0);
                msg.setActivityId(getActivityId());
                msg.setHomeUserId(cookBoy3Table.getUserId());
                msg.setIntegral(addIntegral);
                msg.setBanquetItemId(cookBoy3Table.getOpenItemId());
                YanQuMessage pbOpenerMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_CHEF_DUEL3_ROBOT_JOIN, msg);
                MessageHelper.sendChannelPacket(cookBoy3Table.getServerId(), cookBoy3Table.getUserId(), pbOpenerMsg);
                cookBoy3Table.setIntegral(cookBoy3Table.getIntegral() + addIntegral);
            }*/
            synchronized (needUpdateTableList){
                if(!needUpdateTableList.contains(cookBoy3Table)){
                    needUpdateTableList.add(cookBoy3Table);
                }
            }

            //结束日志
//            ChefDuelUpUser duelUpUser = chefDuelMap.get(cookBoy3Table.getUserId());
//            CrossAutoLogMgr.add(new LogChefDuel3End(cookBoy3Table.getActivityId(),
//                    cookBoy3Table.getUserId(),
//                    duelUpUser.getCampId(),
//                    cookBoy3Table.getMyOpenTimes(),
//                    endType,
//                    "", 0));

        }

        return cookBoy2EndBanquet;
    }

    private void tableCheck(){
        for(Map<Integer, ChefDuel3Table> userTableMap : cookBoyTableMap.values()){
            for(ChefDuel3Table cookBoy3Table : userTableMap.values()){
                if(cookBoy3Table.getOverTime() != 0)continue;

                    ChefDuel3EndBanquet eatTableRes = null;
                    ChefDuel3OpenItem cookBoy3OpenItem = CrossChefDuelActivityMgr.getChefDuel3OpenItem(getActivityId(),cookBoy3Table.getOpenItemId());
                    if(cookBoy3OpenItem == null){
                        continue;
                    }
                    //时间到了结束//座位坐满了结束
                    if(System.currentTimeMillis() - cookBoy3Table.getOpenTime() > cookBoy3OpenItem.getMinute() * 60 * 1000 ||
                            cookBoy3Table.getChefDuel3JoinerMap().size() >= cookBoy3OpenItem.getEatNum()){
                        synchronized (getBanquetLock(cookBoy3Table.getNo())){
                            eatTableRes = endTable(cookBoy3Table);
                        }
                    }
                    //不会结束，除非时间到了或者坐满了
                    /*if(!CrossChefDuelActivityMgr.isActivityMatchTime(activityInfo)){
                        eatTableRes = endTable(cookBoy3Table);
                    }*/
                    if(eatTableRes != null){
                        syncTableServer(cookBoy3Table);
                    }
                }
            }
    }

    //按照排名给桌子排下序
    private void rankToPos(){
        List<ChefDuelUpUser> upUserList = new ArrayList<>(chefDuelMap.values());
        upUserList.sort(new PosSort());
        int rank = 1;
        for(ChefDuelUpUser cookBoyUpUser : upUserList){
            cookBoyUpUser.setRank(rank);
            cookBoyUpUser.setPos(rank);
            rank++;
        }
    }

    public void setActivityInfo(ActivityInfo activityInfo){
        this.activityInfo = activityInfo;
    }

    public int selectCampId(long serverId, long playerId, int campId) {
        ChefDuelUpUser duelUpUser = chefDuelMap.get(playerId);
        boolean isNew = false;
        if(duelUpUser == null){
            synchronized (getUserLocker(playerId)){
                duelUpUser = chefDuelMap.get(playerId);
                if(duelUpUser == null){
                    duelUpUser = new ChefDuelUpUser();
                    duelUpUser.setActivityId(activityInfo.getActivityId());
                    duelUpUser.setServerId(serverId);
                    duelUpUser.setUserId(playerId);
                    duelUpUser.setPreRank(-1);

                    //瞎鸡巴赋值一下，这里的位置顺序是按照积分排名的
                    duelUpUser.setPos(chefDuelMap.size() + 1);
                    duelUpUser.setType(3);
                    duelUpUser.setForbiddenSpoonList(new ArrayList<>());
                    isNew = true;
                    chefDuelMap.put(duelUpUser.getUserId(), duelUpUser);
                    synchronized (needInsertUserList){
                        if(!needInsertUserList.contains(duelUpUser)){
                            needInsertUserList.add(duelUpUser);
                        }
                    }
                }
            }
        }
        if(duelUpUser.getSupportCampId() > 0){
            return GameErrorCode.E_CHEF_DUEL2_CAMP_CHANGE_ERROR;
        }
        duelUpUser.setSupportCampId(campId);
        if(!isNew) {
            synchronized (needUpdateUserList) {
                if (!needUpdateUserList.contains(duelUpUser)) {
                    needUpdateUserList.add(duelUpUser);
                }
            }
        }
        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.S_CROSS_CHEF_DUEL3_SUPPORT_CAMP,
                ChefDuelProto.ChefDuel2CampSelectRespMsg.newBuilder().setRet(0).setCampId(campId).setActivityId(duelUpUser.getActivityId())));
        return 0;
    }

    public int campPopNum(long serverId, long playerId) {
        ChefDuelProto.ChefDuel2CampListRespMsg.Builder clientMsg = ChefDuelProto.ChefDuel2CampListRespMsg.newBuilder();
        clientMsg.setRet(0);
        int camp1 = campCountMap.getOrDefault(1, 0);
        clientMsg.addCampNum(camp1);
        int camp2 = campCountMap.getOrDefault(2, 0);
        clientMsg.addCampNum(camp2);
        MessageHelper.sendPacket(serverId, playerId, YanQuMessageUtils.buildMessage(Protocol.U_CHEF_DUEL3_CAMP_POPULARITY, clientMsg));
        return 0;
    }

    private Map<Long, Object> userLockerMap = new ConcurrentHashMap<>();

    public Object getUserLocker(long userId){
        if(!userLockerMap.containsKey(userId)){
            synchronized (userLockerMap){
                if(!userLockerMap.containsKey(userId)){
                    userLockerMap.put(userId, new Object());
                }
            }
        }
        return userLockerMap.get(userId);
    }

    public int getChefDuel3CampRank(long serverId, long playerId) {
        ChefDuelUpUser userData = chefDuelMap.get(playerId);
        if (userData == null || userData.getSupportCampId() <= 0) {
            return GameErrorCode.E_CHEF_DUEL2_USER_NOT_ABLE;
        }
        synchronized (getUserLocker(playerId)) {
            if(userData.getCampRewardGet() == 1){
                return GameErrorCode.E_ACTIVITY_REWARD_IS_GET;
            }
            userData.setCampRewardGet(1);
            int myRank = -1;
            int num = 0;
            for (CampRank rank : campRankListModel.getRankList()) {
                num++;
                if (rank.getId() == userData.getSupportCampId()) {
                    myRank = num;
                    break;
                }
            }
            ChefDuelProto.CrossChefDuelGetCampRankRewardRespMsg.Builder builder = ChefDuelProto.CrossChefDuelGetCampRankRewardRespMsg.newBuilder();
            builder.setRet(0);
            builder.setActivityId(getActivityInfo().getActivityId());
//            builder.setConditionType(eGamePlayerEventType.ChefDuel2CrossCampRank.getValue());
            builder.setRank(myRank);
            sendPacket(serverId, Protocol.S_CHEF_DUEL3_CAMP_RANK_REWARD_FROM_CROSS, builder, playerId);
        }
        synchronized (needUpdateUserList){
            if(!needUpdateUserList.contains(userData)){
                needUpdateUserList.add(userData);
            }
        }
        return 0;
    }


    protected void sendPacket(long serverId, int code, AbstractMessage.Builder<?> messageBuilder, long userId) {
        YanQuMessage message = YanQuMessageUtils.buildMessage(code, messageBuilder);
        MessageHelper.sendPacket(serverId, userId, message);
    }


    //补发阵营奖励
    public void sendCampRankReward() {
        List<ChefDuelUpUser> list = new ArrayList<>();
        for (Map.Entry<Long, ChefDuelUpUser> entry : chefDuelMap.entrySet()) {
            ChefDuelUpUser upUser = entry.getValue();
            if(upUser.getSupportCampId() <= 0){
                continue;
            }
            if(upUser.getCampRewardGet() == 1){
                continue;
            }
            upUser.setCampRewardGet(1);
            list.add(upUser);
        }

        if(!list.isEmpty()){
            synchronized (needUpdateUserList){
                needUpdateUserList.addAll(list);
            }
            Map<Long, Map<Integer, Set<Long>>> serverRankListMap = new HashMap<>();
            for (ChefDuelUpUser upUser : list) {
                if(!serverRankListMap.containsKey(upUser.getServerId())){
                    serverRankListMap.put(upUser.getServerId(), new HashMap<>());
                }
                int myRank = campRankListModel.getMyRank(upUser.getSupportCampId());
                if(!serverRankListMap.get(upUser.getServerId()).containsKey(myRank)){
                    serverRankListMap.get(upUser.getServerId()).put(myRank, new HashSet<>());
                }
                serverRankListMap.get(upUser.getServerId()).get(myRank).add(upUser.getUserId());
            }
            if(!serverRankListMap.isEmpty()){
                for (Map.Entry<Long, Map<Integer, Set<Long>>> entry : serverRankListMap.entrySet()) {
                    ChefDuelProto.CrossChefDuelCampRewardSendMsg.Builder msg = ChefDuelProto.CrossChefDuelCampRewardSendMsg.newBuilder();
                    msg.setActivityId(activityInfo.getActivityId());
                    for (Map.Entry<Integer, Set<Long>> setEntry : entry.getValue().entrySet()) {
                        ChefDuelProto.ChefDuelCampRewardTemp.Builder builder = ChefDuelProto.ChefDuelCampRewardTemp.newBuilder();
                        builder.setRank(setEntry.getKey());
                        builder.addAllUserId(setEntry.getValue());
                        builder.setReward(CrossChefDuelActivityMgr.getChefDuel3CampReward(activityInfo.getActivityId(), setEntry.getKey()));
                        msg.addRank(builder);
                    }
                    MessageHelper.sendPacket(entry.getKey(), 0, YanQuMessageUtils.buildMessage(Protocol.S_CHEF_DUEL3_CAMP_REWARD_SEND_FROM_CROSS, msg));
                }
            }
        }
    }

    public void uploadChefDuelScore(List<ChefDuelProto.CrossChefDuel2ScoreTemp> scoreList) {
        for (ChefDuelProto.CrossChefDuel2ScoreTemp temp : scoreList) {
            ChefDuelUpUser user = chefDuelMap.get(temp.getUserId());
            if(user != null && user.getCampId() > 0){
                //分数有变化才入库
                if(user.getRankIntegral() != temp.getScore()) {
                    user.setRankIntegral(temp.getScore());
                    user.setRankTime(temp.getTime());
                    synchronized (needUpdateUserList){
                        if(!needUpdateUserList.contains(user)){
                            needUpdateUserList.add(user);
                        }
                    }
                }
            }
        }
    }

    //从大到小
    static class PosSort implements Comparator<ChefDuelUpUser> {
        @Override
        public int compare(ChefDuelUpUser o1, ChefDuelUpUser o2) {
            if (o1.getLastScore() == o2.getLastScore()) {
                return 0;
            }
            if (o1.getLastScore() <= o2.getLastScore()) {
                return 1;
            }
            return -1;
        }
    }

    public void addPromotionUser(Map<Integer,Long> userMap){
        for(int rank : userMap.keySet()){
            long userId = userMap.get(rank);
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userId);
            if(!chefDuelMap.containsKey(userId)){
                ChefDuelUpUser cookBoyUp = new ChefDuelUpUser();
                cookBoyUp.setActivityId(activityInfo.getActivityId());
                cookBoyUp.setServerId(userBaseInfo.getServerId());
                cookBoyUp.setUserId(userId);
                cookBoyUp.setPos(rank);
                cookBoyUp.setType(3);
                chefDuelMap.put(cookBoyUp.getUserId(),cookBoyUp);
                synchronized (needInsertUserList){
                    if(!needInsertUserList.contains(cookBoyUp)){
                        needInsertUserList.add(cookBoyUp);
                    }
                }
            }
        }
    }

    public void addPromotionUser(long serverId,List<ChefDuelProto.CrossChefDuelWindUpCookerTempMsg> userListMsg){
        boolean sortFlag = false;
        for(ChefDuelProto.CrossChefDuelWindUpCookerTempMsg tempMsg : userListMsg) {
            long userId = tempMsg.getUserId();
            if (tempMsg.hasPlayerBaseData()) {
                UserBaseInfo userBaseInfo = PlayerBasePb.parseToUserBaseInfo(tempMsg.getPlayerBaseData());
                CrossUserMgr.updateUserBaseInfo(userId, userBaseInfo);
            }
            synchronized (getUserLocker(userId)) {
                ChefDuelUpUser chefDuelUpUser = chefDuelMap.get(userId);
                if(chefDuelUpUser == null){
                    sortFlag = true;
                    chefDuelUpUser = new ChefDuelUpUser();
                    chefDuelUpUser.setActivityId(activityInfo.getActivityId());
                    chefDuelUpUser.setServerId(serverId);
                    chefDuelUpUser.setUserId(userId);
                    chefDuelUpUser.setPreRank(tempMsg.getRank());

                    //根据排名给阵营
                    if(tempMsg.getRank() <= 0){
                        chefDuelUpUser.setCampId(new Random().nextInt(2) + 1);
                    }else {
                        if(chefDuelUpUser.getCampId() <= 0){
                            int i = tempMsg.getRank() % 4;
                            if(i < 2){
                                chefDuelUpUser.setCampId(1);
                            }else {
                                chefDuelUpUser.setCampId(2);
                            }
                        }
                    }

                    //瞎鸡巴赋值一下，这里的位置顺序是按照积分排名的
                    chefDuelUpUser.setPos(chefDuelMap.size() + 1);
                    chefDuelUpUser.setType(3);
                    if(tempMsg.getScore() != 0){
                        chefDuelUpUser.setLastScore(tempMsg.getScore());
                    }
                    chefDuelUpUser.setForbiddenSpoonList(new ArrayList<>());
                    chefDuelMap.put(chefDuelUpUser.getUserId(),chefDuelUpUser);
                    synchronized (needInsertUserList){
                        if(!needInsertUserList.contains(chefDuelUpUser)){
                            needInsertUserList.add(chefDuelUpUser);
                        }
                    }
                }else {

                    chefDuelUpUser.setPreRank(tempMsg.getRank());
                    if(tempMsg.getScore() != 0){
                        chefDuelUpUser.setLastScore(tempMsg.getScore());
                    }

                    //根据排名给阵营
                    if(chefDuelUpUser.getCampId() <= 0){
                        if(tempMsg.getRank() <= 0){
                            chefDuelUpUser.setCampId(new Random().nextInt(2) + 1);
                        }else {
                            int i = tempMsg.getRank() % 4;
                            if(i < 2){
                                chefDuelUpUser.setCampId(1);
                            }else {
                                chefDuelUpUser.setCampId(2);
                            }
                        }
                    }

                    synchronized (needUpdateUserList){
                        if(!needUpdateUserList.contains(chefDuelUpUser)){
                            needUpdateUserList.add(chefDuelUpUser);
                        }
                    }
                }
            }
        }
        if(sortFlag){
            rankToPos();
        }
    }

    private Object getBanquetLock(int no){
        if(!lockMap.containsKey(no)){
            synchronized (lockMap) {
                if (!lockMap.containsKey(no))
                    lockMap.put(no,new Object());
            }
        }
        return lockMap.get(no);
    }

    public int joinBanquet(long serverId,long joinUserId,long homeUserId,int banquetId){
     //   tableCheck();
            if(!cookBoyTableMap.containsKey(homeUserId)){
                return GameErrorCode.E_CHEF_DUEL3_USER_NOT_MATCH;
            }
            Map<Integer,ChefDuel3Table> cookBoy3TableMap = cookBoyTableMap.get(homeUserId);
            if(!cookBoy3TableMap.containsKey(banquetId)){
                return GameErrorCode.E_CHEF_DUEL3_BANQUET_NOT_FOUND;
            }
            ChefDuel3Table cookBoy3Table = cookBoy3TableMap.get(banquetId);
            ChefDuel3OpenItem cookBoy3OpenItem = CrossChefDuelActivityMgr.getChefDuel3OpenItem(getActivityId(),cookBoy3Table.getOpenItemId());
            if(cookBoy3OpenItem == null){
                return GameErrorCode.E_CHEF_DUEL3_OPEN_BANQUET_ITEM_NOT_FOUND;
            }
            if(System.currentTimeMillis() > cookBoy3Table.getOpenTime() + cookBoy3OpenItem.getMinute() * 60 * 1000){
                return GameErrorCode.E_CHEF_DUEL3_BANQUET_OVER;
            }
            /*if(cookBoy3Table.getChefDuel3JoinerMap().size() >= cookBoy3OpenItem.getEatNum()){
                return GameErrorCode.E_CHEF_DUEL3_USER_JOIN_FULL;
            }*/
            /*if(!CrossChefDuelActivityMgr.isActivityMatchTime(activityInfo)){
                return GameErrorCode.E_CHEF_DUEL3_ACTIVITY_NOT_RUNNING;
            }*/
        int size = 0;
        synchronized (getBanquetLock(banquetId)){
            Map<Integer, Long> joinerMap = cookBoy3Table.getChefDuel3JoinerMap();
            if(joinerMap.containsValue(joinUserId)){
                return GameErrorCode.E_CHEF_DUEL3_TABLE_IS_JOIN;
            }
                joinerMap.put(joinerMap.size() + 1,joinUserId);
                cookBoy3Table.setChefDuel3JoinerMap(joinerMap);
                size = cookBoy3Table.getChefDuel3JoinerMap().size();
        }

        int campId = 0;
        ChefDuelUpUser upUser = chefDuelMap.get(joinUserId);
        if(upUser != null){
            campId = upUser.getCampId();
        }
            ChefDuelProto.CrossChefDuel3JoinBanquetMsg.Builder msg = ChefDuelProto.CrossChefDuel3JoinBanquetMsg.newBuilder();
            msg.setRet(0);
            msg.setActivityId(getActivityId());
            msg.setJoinerUserId(joinUserId);
            msg.setHomeUserId(homeUserId);
            msg.setTimes(cookBoy3Table.getMyOpenTimes());
            msg.setOpenCampId(campId);
            msg.setIntegral((int)cookBoy3OpenItem.getIntegral());
            msg.setBanquetItemId(cookBoy3Table.getOpenItemId());
            //发给开宴会的和参加宴会的人给他们加奖励和积分
            //1.宴会人满了就可以开下一场，但是时间还没到可以继续坐人，坐人只给参加者发奖励，不给开宴者家积分
            //或者在比赛时间才加积分
            if(size <= cookBoy3OpenItem.getEatNum() &&
                        CrossChefDuelActivityMgr.isActivityMatchTime(activityInfo) &&
                        CrossChefDuelActivityMgr.activityInTime(activityInfo)){
                synchronized (getBanquetLock(banquetId)) {
                    cookBoy3Table.setIntegral(cookBoy3Table.getIntegral()+cookBoy3OpenItem.getIntegral());
                }
                    YanQuMessage pbOpenerMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_CHEF_DUEL3_JOIN_OPENER, msg);
                    MessageHelper.sendPacket(cookBoy3Table.getServerId(), homeUserId, pbOpenerMsg);
                }
                YanQuMessage pbJoinerMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_CHEF_DUEL3_JOIN_JOINER, msg);
                MessageHelper.sendPacket(serverId, joinUserId, pbJoinerMsg);
                synchronized (needUpdateTableList){
                    if (!needUpdateTableList.contains(cookBoy3Table)) {
                        needUpdateTableList.add(cookBoy3Table);
                    }
                }
                synchronized (syncTableList){
                    if (!syncTableList.contains(cookBoy3Table)) {
                        syncTableList.add(cookBoy3Table);
                    }
                }
                synchronized (needSyncCookerList){
                    if(!needSyncCookerList.contains(chefDuelMap.get(homeUserId))){
                        needSyncCookerList.add(chefDuelMap.get(homeUserId));
                    }
            }
       // tableCheck();
        return 0;
    }

    private boolean isOpenTable(long homeUserId){


        Map<Integer, ChefDuel3Table> tableMap = cookBoyTableMap.get(homeUserId);
        for(ChefDuel3Table cookBoy3Table : tableMap.values()){
            ChefDuel3EndBanquet eatTableRes = null;
            ChefDuel3OpenItem cookBoy3OpenItem = CrossChefDuelActivityMgr.getChefDuel3OpenItem(getActivityId(),cookBoy3Table.getOpenItemId());
            if(cookBoy3OpenItem == null){
                continue;
            }
            if(System.currentTimeMillis() - cookBoy3Table.getOpenTime() > cookBoy3OpenItem.getMinute() * 60 * 1000 ||
                    cookBoy3Table.getChefDuel3JoinerMap().size() >= cookBoy3OpenItem.getEatNum()){
                synchronized (getBanquetLock(cookBoy3Table.getNo())){
                    eatTableRes = endTable(cookBoy3Table);
                }
            }
            //不会结束，除非时间到了或者坐满了
                    /*if(!CrossChefDuelActivityMgr.isActivityMatchTime(activityInfo)){
                        eatTableRes = endTable(cookBoy3Table);
                    }*/
            if(eatTableRes != null){
                syncTableServer(cookBoy3Table);
            }
         if(cookBoy3Table.getOverTime() == 0){
             return true;
         }
        }
        return false;
    }

    private ChefDuel3Table initChefDuel3Banquet(long serverId,long userId,int itemId,int no){
        ChefDuel3Table newOne = new ChefDuel3Table();
        newOne.setActivityId(activityInfo.getActivityId());
        newOne.setServerId(serverId);
        newOne.setUserId(userId);
        newOne.setOpenItemId(itemId);
        newOne.setOpenTime(System.currentTimeMillis());
        newOne.setOverTime(0);
        newOne.setIntegral(0);
        newOne.setJoinerData("{}");
        newOne.setNo(no);

        return newOne;
    }

    private int getTableCount(){
        int count = 0;
        for(Map<Integer, ChefDuel3Table> userMap : cookBoyTableMap.values()){
            count += userMap.size();
        }
        return count;
    }

    private int getTableCount(long userId){
        int count = 0;
        Map<Integer, ChefDuel3Table> map = cookBoyTableMap.get(userId);
        if(map != null){
            count = map.size();
        }
        return count;
    }

    public void openBanquet(long serverId,long userId,int itemId){
     //   tableCheck();
        ChefDuelProto.CrossChefDuel3OpenBanquetRespMsg.Builder msg = ChefDuelProto.CrossChefDuel3OpenBanquetRespMsg.newBuilder();
        msg.setActivityId(getActivityId());
        msg.setUserId(userId);
        msg.setItemId(itemId);
        int ret = 0;
        if(!cookBoyTableMap.containsKey(userId)){
            cookBoyTableMap.put(userId,new ConcurrentHashMap<>());
        }
        if(isOpenTable(userId)){
            ret = GameErrorCode.E_CHEF_DUEL3_IS_OPEN_BANQUET;
        }
        if(ret == 0){
            ChefDuel3Table newOne = initChefDuel3Banquet(serverId,userId,itemId, getTableCount() + 1);
            newOne.setMyOpenTimes(getTableCount(userId) + 1);
            cookBoyTableMap.get(userId).put(newOne.getNo(),newOne);
            synchronized (needInsertTableList){
                if(!needInsertTableList.contains(newOne)){
                    needInsertTableList.add(newOne);
                }
            }
            synchronized (syncOpenList){
                syncOpenList.add(newOne);
            }
            synchronized (needSyncCookerList){
                if(!needSyncCookerList.contains(chefDuelMap.get(userId))){
                    needSyncCookerList.add(chefDuelMap.get(userId));
                }
            }
            syncTableServer(newOne);
            timeSyncBanquetOpenServer();
            timeSyncBanquetUserServer();
            msg.setBanquetId(newOne.getNo());
            ChefDuelUpUser cookData = chefDuelMap.get(userId);
            CrossAutoLogMgr.add(new LogChefDuel3Open(
                    newOne.getActivityId(),
                    userId,
                    cookData.getCampId(),
                    itemId + "=1",
                    getUserBanquetCount(userId)
            ));
        }
        msg.setRet(ret);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_CHEF_DUEL3_OPEN_BANQUET, msg);
        MessageHelper.sendPacket(serverId, userId, pbMsg);
    }

    //同步这个服参加了哪些人，用来判断是不是自己可以参加
    private List<Long> getServerAllUserIdList(long serverId,ChefDuel3Table table){
        List<Long> resList = new ArrayList<>();
        for(long userId : new ArrayList<>(table.getChefDuel3JoinerMap().values())){
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(userId);
            if(userBaseInfo != null && userBaseInfo.getServerId() == serverId){
                resList.add(userId);
            }
        }
        return resList;
    }

    public void syncTableServer(ChefDuel3Table newOne){
        List<Long> campScoreList = getCampScoreList();
        for(long serverId : activityInfo.getServerIdList()){
            ChefDuelProto.CrossChefDuel3TableSyncMsg.Builder respMsg = ChefDuelProto.CrossChefDuel3TableSyncMsg.newBuilder();
            respMsg.setActivityId(getActivityId());
            ChefDuelProto.ChefDuel3CookerCrossTempMsg.Builder tempTableMsg = parseChefDuel3CookerCrossTempMsg(serverId, chefDuelMap.get(newOne.getUserId()).getRank(),newOne);
            if(tempTableMsg == null){
                continue;
            }
            respMsg.addTableList(tempTableMsg);
            respMsg.addAllCampScore(campScoreList);
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_CHEF_DUEL3_TABLE_SYNC, respMsg);
            MessageHelper.sendPacket(serverId, 0, pbMsg);
        }
    }

    public List<Long> getCampScoreList(){
        List<Long> list = new ArrayList<>();
        for (int i = 1; i <= 2; i++) {
            for (CampRank campRank : campRankListModel.getRankList()) {
                if (campRank.getId() == i) {
                    list.add(campRank.getValue());
                }
            }
        }
        return list;
    }


    public ChefDuelProto.ChefDuel3CookerCrossTempMsg.Builder parseChefDuel3CookerCrossTempMsg(long serverId, int rank, ChefDuel3Table cookBoy3Table) {
        ChefDuelProto.ChefDuel3CookerCrossTempMsg.Builder tempTableMsg = ChefDuelProto.ChefDuel3CookerCrossTempMsg.newBuilder();
        UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(cookBoy3Table.getUserId());
        if(userBaseInfo == null){
            return null;
        }
        tempTableMsg.setUserInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
        tempTableMsg.setRank(rank);
        tempTableMsg.setUserId(cookBoy3Table.getUserId());
        ChefDuelUpUser chefDuelUpUser = chefDuelMap.get(cookBoy3Table.getUserId());
        if(chefDuelUpUser != null){
            tempTableMsg.setCampId(chefDuelUpUser.getCampId());
        }
        ChefDuel3OpenItem cookBoy3OpenItem = CrossChefDuelActivityMgr.getChefDuel3OpenItem(getActivityId(),cookBoy3Table.getOpenItemId());
        if(System.currentTimeMillis() - cookBoy3Table.getOpenTime() <= cookBoy3OpenItem.getMinute() * 60 * 1000){
            tempTableMsg.setOpenItemId(cookBoy3Table.getOpenItemId());
            tempTableMsg.setOpenTime((int)(cookBoy3Table.getOpenTime()/1000));
            tempTableMsg.setBanquetId(cookBoy3Table.getNo());
            tempTableMsg.setUserNum(cookBoy3Table.getChefDuel3JoinerMap().size());
            tempTableMsg.addAllUserLit(getServerAllUserIdList(serverId,cookBoy3Table));
        }else{
            tempTableMsg.setOpenItemId(0);
            tempTableMsg.setOpenTime(0);
            tempTableMsg.setBanquetId(0);
            tempTableMsg.setUserNum(0);
            tempTableMsg.addAllUserLit(new ArrayList<>());
        }
        tempTableMsg.setBanquetCount(getUserBanquetCount(cookBoy3Table.getUserId()));
        return tempTableMsg;
    }

    public void syncTableServer(List<ChefDuel3Table> syncTableList){
        Map<Long,ChefDuel3Table> needSync = new ConcurrentHashMap<>();
        for(ChefDuel3Table cookBoy3Table : syncTableList){
            if(needSync.containsKey(cookBoy3Table.getUserId())){
                if(cookBoy3Table.getNo() > needSync.get(cookBoy3Table.getUserId()).getNo()){
                    needSync.put(cookBoy3Table.getUserId(),cookBoy3Table);
                }
            }else{
                needSync.put(cookBoy3Table.getUserId(),cookBoy3Table);
            }
        }
        for(long serverId : activityInfo.getServerIdList()){
            ChefDuelProto.CrossChefDuel3TableSyncMsg.Builder respMsg = ChefDuelProto.CrossChefDuel3TableSyncMsg.newBuilder();
            respMsg.setActivityId(getActivityId());
            for(ChefDuel3Table one : needSync.values()){
                ChefDuelProto.ChefDuel3CookerCrossTempMsg.Builder tempTableMsg = parseChefDuel3CookerCrossTempMsg(serverId, chefDuelMap.get(one.getUserId()).getRank(),one);
                if(tempTableMsg == null){
                    continue;
                }
                respMsg.addTableList(tempTableMsg);
            }
            respMsg.addAllCampScore(getCampScoreList());
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_CHEF_DUEL3_TABLE_SYNC, respMsg);
            MessageHelper.sendPacket(serverId, 0, pbMsg);
        }
    }


    private ChefDuel3Table getUserOpenBanquet(long homeUserId){
        if(!cookBoyTableMap.containsKey(homeUserId)){
            return null;
        }
        Map<Integer,ChefDuel3Table> tableMap = cookBoyTableMap.get(homeUserId);
        ChefDuel3Table returnTable = null;
        Map<Integer, ChefDuel3OpenItem> cookBoy3OpenItemMap = new HashMap<>();
        for(ChefDuel3Table table : tableMap.values()){
            if (System.currentTimeMillis() - table.getOpenTime() > 3600 * 1000) {
                continue;
            }
            ChefDuel3OpenItem cookBoy3OpenItem  = cookBoy3OpenItemMap.get(table.getOpenItemId());
            if (cookBoy3OpenItem == null) {
                cookBoy3OpenItem   = CrossChefDuelActivityMgr.getChefDuel3OpenItem(getActivityId(),table.getOpenItemId());
                if (cookBoy3OpenItem != null) {
                    cookBoy3OpenItemMap.put(table.getOpenItemId(), cookBoy3OpenItem);
                }
            }
            if(cookBoy3OpenItem == null){
                continue;
            }
            if(System.currentTimeMillis() - table.getOpenTime() < cookBoy3OpenItem.getMinute() * 60 * 1000){
                //返回最新的那张
                if(returnTable == null || returnTable.getNo() < table.getNo()){
                    returnTable = table;
                }
            }
        }
        return returnTable;
    }

    private int getUserBanquetCount(long homeUserId){
        if(!cookBoyTableMap.containsKey(homeUserId)){
            return 0;
        }
        return cookBoyTableMap.get(homeUserId).size();
    }

    private int getUserAllJoinCount(long homeUserId){
        if(!cookBoyTableMap.containsKey(homeUserId)){
            return 0;
        }
        int count = 0;
        for(ChefDuel3Table cookBoy3Table : cookBoyTableMap.get(homeUserId).values()){
            count += cookBoy3Table.getChefDuel3JoinerMap().size();
        }
        return count;
    }

    public void syncCooker3Table(long serverId,long userId,long homeUserId){
      //  tableCheck();
        ChefDuelProto.ChefDuel3CookerRespMsg.Builder respMsg = ChefDuelProto.ChefDuel3CookerRespMsg.newBuilder();
        int ret = 0;
        Map<Long, ChefDuelUpUser> syncMap = new ConcurrentHashMap<>();
        if(homeUserId == 0){
            respMsg.setIsSync(false);
            syncMap = chefDuelMap;
        }else{
            respMsg.setIsSync(true);
            if(chefDuelMap.containsKey(homeUserId)){
                syncMap.put(chefDuelMap.get(homeUserId).getUserId(), chefDuelMap.get(homeUserId));
            }else{
                ret = GameErrorCode.E_CHEF_DUEL3_USER_NOT_MATCH;
            }
        }
        for(ChefDuelUpUser cookBoyUpUser : new ArrayList<>(syncMap.values())){
            if(cookBoyUpUser.getCampId() <= 0){
                continue;
            }
            ChefDuelProto.ChefDuel3CookerTempMsg.Builder tempMsg = ChefDuelProto.ChefDuel3CookerTempMsg.newBuilder();
            tempMsg.setRank(cookBoyUpUser.getRank());
            tempMsg.setUserId(cookBoyUpUser.getUserId());
            tempMsg.setCampId(cookBoyUpUser.getCampId());
            ChefDuel3Table table = getUserOpenBanquet(cookBoyUpUser.getUserId());
            if(table == null){
                tempMsg.setOpenItemId(0);
                tempMsg.setOpenTime(0);
                tempMsg.setBanquetId(0);
                tempMsg.setCanEat(false);
                tempMsg.setUserNum(0);
            }else{
                tempMsg.setOpenItemId(table.getOpenItemId());
                tempMsg.setOpenTime((int)(table.getOpenTime()/1000));
                tempMsg.setBanquetId(table.getNo());
                tempMsg.setCanEat(!table.getChefDuel3JoinerMap().containsValue(userId));
                tempMsg.setUserNum(table.getChefDuel3JoinerMap().size());
            }
//            tempMsg.setUserNum(getUserAllJoinCount(cookBoyUpUser.getUserId()));
            tempMsg.setBanquetCount(getUserBanquetCount(cookBoyUpUser.getUserId()));
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(cookBoyUpUser.getUserId());
            if(userBaseInfo == null){
                continue;
            }
            tempMsg.setUserInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
            respMsg.addCookerList(tempMsg);
        }
        respMsg.setRet(ret);
        respMsg.addAllCampScore(getCampScoreList());

        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.U_CHEF_DUEL3_GET_TABLE_USER, respMsg);
        MessageHelper.sendPacket(serverId, userId, pbMsg);
    }

    public void timerTask(){
        tableCheck();
        timeSyncTableServer();
        timeSyncBanquetUserServer();

        //活动结束了清掉数据
        long nowTime = System.currentTimeMillis() / 1000;
        if(nowTime >= activityInfo.getEndShowTime() + 5 * 60 && cookBoyTableMap.size() > 0){
            logger.info("阶段三清除活动数据"+getActivityId()+"大小"+cookBoyTableMap.size());
            cookBoyTableMap.clear();
        }

        //内存要炸了就移除不是今天开的宴会吧吧
        /*if(nowTime >= activityInfo.getEndTime() + 10 * 60){
            long todayZeroTimestamp = DateHelper.getTodayZeroTimeStamp();
            for(long userId : cookBoyTableMap.keySet()){
                Map<Integer, ChefDuel3Table> tableMap = cookBoyTableMap.get(userId);
                for(ChefDuel3Table table : tableMap.values()){
                    if(todayZeroTimestamp != DateHelper.getZeroTimeStamp(table.getOpenTime())){
                        cookBoyTableMap.get(userId).remove(table.getNo());
                    }
                }
            }
        }*/
    }

    public void timerTask4Stat() {

        int currentSecond = DateHelper.getCurrentSecond();
        //活动结束4分钟后不再统计
        if(currentSecond >= this.activityInfo.getEndTime() + 4 * DateHelper.MINUTE_SECONDS){
            return;
        }
        
        Map<Integer, Long> campScoreMap = new HashMap<>();
        Map<Integer, Long> campScoreLastTimeMap = new HashMap<>();
        Map<Integer, LinkedList<CrossChefDuel2Rank>> rankList = new HashMap<>();
        for (Map.Entry<Long, ChefDuelUpUser> entry : chefDuelMap.entrySet()) {
            int campId = entry.getValue().getCampId();
            if(campId <= 0){
                continue;
            }
            
            long score = campScoreMap.getOrDefault(campId, 0L);
            campScoreMap.put(campId, score + entry.getValue().getRankIntegral());

            long time = campScoreLastTimeMap.getOrDefault(campId, 0L);
            if(time < entry.getValue().getRankTime() && entry.getValue().getRankTime() > 0 && entry.getValue().getRankIntegral() > 0){
                campScoreLastTimeMap.put(campId, entry.getValue().getRankTime());
            }

            //阵营玩家榜单
            if(!rankList.containsKey(campId)){
                rankList.put(campId, new LinkedList<>());
            }
            rankList.get(campId).add(new CrossChefDuel2Rank(entry.getValue().getUserId(), entry.getValue().getRankIntegral(), entry.getValue().getRankTime()));
        }

        for (Map.Entry<Integer, Long> entry : campScoreMap.entrySet()) {
            if(entry.getValue() > 0) {
                long time = campScoreLastTimeMap.getOrDefault(entry.getKey(), System.currentTimeMillis());
                campRankListModel.rankChange(new CampRank(entry.getKey(), entry.getValue(), time));
            }
        }

        for (Map.Entry<Integer, LinkedList<CrossChefDuel2Rank>> entry : rankList.entrySet()) {
            CrossChefDuel2RankListModel model = campUserRankMap.get(entry.getKey());
            model.setRankList(entry.getValue());
        }
        
        Map<Integer, Integer> campCountMap = new HashMap<>();
        for (Map.Entry<Long, ChefDuelUpUser> entry : chefDuelMap.entrySet()) {
            int campId = entry.getValue().getSupportCampId();
            if (campId <= 0) {
                continue;
            }
            //阵营人气
            int old = campCountMap.getOrDefault(campId, 0);
            campCountMap.put(campId, old + 1);
        }
        this.campCountMap = campCountMap;

    }

    public void syncLoginData(long serverId,long userId){
        loginSyncBanquetUser(serverId,userId);
    }

    public void noticeTimerTask(){
        timeSyncBanquetOpenServer();
    }

    private void timeSyncTableServer(){
        //同步宴会参加者的变化给所有区服
        List<ChefDuel3Table> list = new ArrayList<>();
        synchronized (syncTableList){
            if(syncTableList.size() > 0){
                list = new ArrayList<>(syncTableList);
                syncTableList.clear();
            }
        }
        if(list.size() > 0){
            syncTableServer(list);
        }
    }

    private void timeSyncBanquetUserServer(){
        synchronized (needSyncCookerList) {
            if(needSyncCookerList.size() > 0){
                ChefDuelProto.ChefDuel3UserRewardSyncMsg.Builder msg = CrossChefDuelPb.parseChefDuel3UserRewardSyncMsg(getActivityId(), chefDuelMap,cookBoyTableMap);
                for(long serverId : activityInfo.getServerIdList()){
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_CHEF_DUEL3_BANQUET_USER_DATA_SYNC, msg);
                    MessageHelper.sendPacket(serverId, 0, pbMsg);
                }
                needSyncCookerList.clear();
            }
        }
    }

    private void loginSyncBanquetUser(long serverId,long userId){
          ChefDuelProto.ChefDuel3UserRewardSyncMsg.Builder msg = CrossChefDuelPb.parseChefDuel3UserRewardSyncMsg(getActivityId(), chefDuelMap,cookBoyTableMap);
          YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_CHEF_DUEL3_BANQUET_USER_DATA_SYNC, msg);
          MessageHelper.sendPacket(serverId, userId, pbMsg);

          syncCooker3Table(serverId,userId,0);
    }

    //全服广播开宴通知
    private void timeSyncBanquetOpenServer(){
        List<ChefDuel3Table> tempList ;
        synchronized (syncOpenList) {
            tempList = new ArrayList<>(syncOpenList);
            syncOpenList.clear();
        }
        if (tempList.isEmpty()) {
            return;
        }

        ChefDuelProto.ChefDuel3BanquetOpenSyncMsg.Builder msg = ChefDuelProto.ChefDuel3BanquetOpenSyncMsg.newBuilder();
        msg.setActivityId(getActivityId());
        for(ChefDuel3Table cookBoy3Table : tempList){
            ChefDuelProto.ChefDuel3BanquetOpenTempMsg.Builder banquetMsg = ChefDuelProto.ChefDuel3BanquetOpenTempMsg.newBuilder();
            banquetMsg.setBanquetId(cookBoy3Table.getNo());
            banquetMsg.setUserId(cookBoy3Table.getUserId());
            banquetMsg.setOpenItemId(cookBoy3Table.getOpenItemId());
            banquetMsg.setOpenTime((int)(cookBoy3Table.getOpenTime()/1000));
            UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(cookBoy3Table.getUserId());
            if(userBaseInfo == null){
                continue;
            }
            banquetMsg.setUserInfo(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
            msg.addBanquetList(banquetMsg);
        }
        for(long serverId : activityInfo.getServerIdList()){
            YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_CROSS_CHEF_DUEL3_OPEN_BANQUET_NOTICE_SYNC, msg);
            MessageHelper.sendPacket(serverId, 0, pbMsg);
        }
    }

    public CrossChefDuel3(ActivityInfo acInfo){
        activityInfo = acInfo;
//		reload();
    }

    public boolean reload() {
        cookBoyTableMap = new CrossChefDuelDaoImpl().getCrossChefDuel3TableMap(activityInfo.getActivityId());
        chefDuelMap = new CrossChefDuelDaoImpl().getCrossChefDuel2UserMap(activityInfo.getActivityId());

        campUserRankMap.put(1, new CrossChefDuel2RankListModel());
        campUserRankMap.put(2, new CrossChefDuel2RankListModel());

        rankToPos();
        return true;
    }

    public boolean save() {
        if(System.currentTimeMillis() < 1629950400000L){
            logger.info("阶段3清除jsonData字符串数据");
            for(Map<Integer, ChefDuel3Table> tableMap: cookBoyTableMap.values()){
                for(ChefDuel3Table cookBoy3Table : tableMap.values()){
                    cookBoy3Table.getJoinerData();
                }
            }
        }
        List<ChefDuel3Table> tempInsertList;
        synchronized (needInsertTableList) {
            tempInsertList = new ArrayList<>(needInsertTableList);
            needInsertTableList.clear();
        }
        if (tempInsertList.size() > 0) {
            new CrossChefDuelDaoImpl().addCrossChefDuel3TableList(tempInsertList);
        }
        List<ChefDuel3Table> tempUpdateList;
        synchronized (needUpdateTableList) {
            tempUpdateList = new ArrayList<>(needUpdateTableList);
            needUpdateTableList.clear();
        }
        if (tempUpdateList.size() > 0) {
            new CrossChefDuelDaoImpl().updateCrossChefDuel3TableList(tempUpdateList);
        }
        List<ChefDuelUpUser> tempChefDuel2UserInsertList;
        synchronized (needInsertUserList){
            tempChefDuel2UserInsertList = new ArrayList<>(needInsertUserList);
            needInsertUserList.clear();
        }
        if(tempChefDuel2UserInsertList.size() > 0){
            new CrossChefDuelDaoImpl().addCrossChefDuelUserList(tempChefDuel2UserInsertList);
        }

        List<ChefDuelUpUser> tempChefDuel2UserUpdateList;
        synchronized (needUpdateUserList){
            tempChefDuel2UserUpdateList = new ArrayList<>(needUpdateUserList);
            needUpdateUserList.clear();
        }
        if(tempChefDuel2UserUpdateList.size() > 0){
            new CrossChefDuelDaoImpl().updateCrossChefDuelUserList(tempChefDuel2UserUpdateList);
        }
        return true;
    }

    public boolean init() {
        return reload();
    }

    public boolean stop() {
        return false;
    }

    public Map<Integer, Integer> getCampCountMap() {
        return campCountMap;
    }

    public CampRankListModel getCampRankListModel() {
        return campRankListModel;
    }

    public Map<Integer, CrossChefDuel2RankListModel> getCampUserRankMap() {
        return campUserRankMap;
    }

    public Map<Long, ChefDuelUpUser> getChefDuelMap() {
        return chefDuelMap;
    }

    /**
     * 预留接口
     */
    public void repair() {

    }

}
